export default {
    name: 'AI_helper',
    data() {
      return {
        PROXY_API_URL: 'http://localhost:3000/api/chat',
        DEFAULT_ROLE: 'default',
        
        // 状态数据
        currentConversationId: this.generateId(),
        currentRole: 'default',
        conversations: {},
        conversationHistory: [],
        isWaitingForResponse: false,
        userInput: '',
        
        // 角色选项
        roleOptions: [
          { value: 'default', label: '智能助手', icon: 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z' },
          { value: 'qa', label: '问答专家', icon: 'M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10zm0-2a8 8 0 1 1 0-16 8 8 0 0 1 0 16zm-1-5h2v2h-2v-2zm0-8h2v6h-2V7z' },
          { value: 'creative', label: '创意写作', icon: 'M12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2z' }
        ],
        
        specialtyOptions: [
          { value: 'medical', label: '医疗咨询', icon: 'M18 8h1a4 4 0 0 1 0 8h-1M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4V8zM6 1v3M10 1v3M14 1v3' },
          { value: 'tech', label: '技术支持', icon: 'M2 3h20v14H2zm0 0v18h20V3zm2 2h16v10H4zm2 2h12v6H6zm2 2h8v2H8z' },
          { value: 'legal', label: '法律咨询', icon: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8' }
        ]
      }
    },
    computed: {
      sortedConversations() {
        return Object.values(this.conversations).sort((a, b) => b.timestamp - a.timestamp)
      },
      displayedMessages() {
        return this.conversationHistory.filter(msg => msg.role !== 'system')
      }
    },
    mounted() {
      this.loadConversations()
      this.startNewConversation()
    },
    methods: {
      generateId() {
        return Date.now().toString() + Math.random().toString(36).substr(2, 9)
      },
      adjustTextareaHeight() {
        const textarea = this.$el.querySelector('textarea')
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px'
      },
      formatMessageText(text) {
        let formatted = text.replace(/\n/g, '<br>')
        formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre>$1</pre>')
        formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>')
        return formatted
      },
      getSystemMessageForRole(role) {
        const roleMessages = {
          'default': '你是一个乐于助人的AI助手，用友好、专业的语气回答问题。',
          'qa': '你是一个知识渊博的问答专家，用准确、简洁的方式回答问题。',
          'creative': '你是一个富有创造力的写作助手，帮助用户进行创意写作和头脑风暴。',
          'medical': '你是一个专业的医疗顾问，提供准确但不替代专业医生的医疗建议。',
          'tech': '你是一个技术专家，帮助解决编程、硬件和软件相关问题。',
          'legal': '你是一个法律顾问，提供一般性法律信息但不构成正式法律建议。'
        }
        return roleMessages[role] || roleMessages['default']
      },
      getTemperatureForRole(role) {
        const roleTemperatures = {
          'default': 0.7,
          'qa': 0.3,
          'creative': 0.9,
          'medical': 0.5,
          'tech': 0.6,
          'legal': 0.4
        }
        return roleTemperatures[role] || 0.7
      },
      getRoleName(role) {
        const roleNames = {
          'default': '智能助手',
          'qa': '问答专家',
          'creative': '创意写作',
          'medical': '医疗咨询',
          'tech': '技术支持',
          'legal': '法律咨询'
        }
        return roleNames[role] || '智能助手'
      },
      async sendMessage() {
        const message = this.userInput.trim()
        if (!message || this.isWaitingForResponse) return
        
        // 添加用户消息
        this.conversationHistory.push({ role: 'user', content: message })
        
        // 如果是第一条消息，创建对话标题
        if (this.conversationHistory.length === 1) {
          this.updateConversationTitle(message)
        }
        
        // 清空输入框并禁用
        this.userInput = ''
        this.isWaitingForResponse = true
        
        try {
          // 获取AI回复
          const aiResponse = await this.getAIResponse()
          
          // 添加AI回复
          this.conversationHistory.push({ role: 'assistant', content: aiResponse })
          
          // 保存对话
          this.saveConversation()
          
          // 滚动到底部
          this.$nextTick(() => {
            this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
          })
        } catch (error) {
          console.error('API请求错误:', error)
          this.conversationHistory.push({ 
            role: 'assistant', 
            content: '抱歉，我遇到了问题。请稍后再试或检查您的网络连接。'
          })
        } finally {
          this.isWaitingForResponse = false
        }
      },
      async getAIResponse() {
        // 构建系统消息
        const systemMessage = this.getSystemMessageForRole(this.currentRole)
        
        // 构建消息数组 (包含系统消息和对话历史)
        const messages = [
          { role: 'system', content: systemMessage },
          ...this.conversationHistory.filter(msg => msg.role !== 'system')
        ]
        
        const response = await fetch(this.PROXY_API_URL, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: 'deepseek-chat',
            messages: messages,
            temperature: this.getTemperatureForRole(this.currentRole),
            max_tokens: 2000
          })
        })
        
        if (!response.ok) {
          throw new Error(`API请求失败: ${response.status}`)
        }
        
        const data = await response.json()
        return data.choices[0].message.content
      },
      selectRole(role) {
        // 更新当前角色
        this.currentRole = role
        
        // 如果是新对话，直接更新系统消息
        if (this.conversationHistory.length <= 1) {
          this.conversationHistory[0] = { 
            role: 'system', 
            content: this.getSystemMessageForRole(role) 
          }
        } else {
          // 否则提示用户需要新建对话
          if (confirm(`切换角色到"${this.getRoleName(role)}"将开始新的对话。是否继续？`)) {
            this.startNewConversation()
          }
        }
      },
      startNewConversation() {
        // 保存当前对话
        if (this.conversationHistory.length > 0) {
          this.saveConversation()
        }
        
        // 创建新对话
        this.currentConversationId = this.generateId()
        this.conversationHistory = [
          { 
            role: 'system', 
            content: this.getSystemMessageForRole(this.currentRole) 
          }
        ]
        
        // 添加欢迎消息
        this.conversationHistory.push({
          role: 'assistant',
          content: `你好！我是${this.getRoleName(this.currentRole)}，有什么可以帮你的吗？`
        })
        
        // 更新历史记录面板
        this.updateHistoryPanel()
      },
      updateConversationTitle(firstMessage) {
        const title = firstMessage.length > 30 
          ? firstMessage.substring(0, 30) + '...' 
          : firstMessage
        
        if (this.conversations[this.currentConversationId]) {
          this.conversations[this.currentConversationId].title = title
        }
      },
      getConversationTitle() {
        // 尝试从对话历史中找第一条用户消息
        const userMessage = this.conversationHistory.find(m => m.role === 'user')
        if (userMessage) {
          return userMessage.content.length > 30 
            ? userMessage.content.substring(0, 30) + '...' 
            : userMessage.content
        }
        
        // 如果没有用户消息，使用默认标题
        return `与${this.getRoleName(this.currentRole)}的对话`
      },
      saveConversation() {
        this.conversations[this.currentConversationId] = {
          id: this.currentConversationId,
          title: this.getConversationTitle(),
          role: this.currentRole,
          history: [...this.conversationHistory],
          timestamp: Date.now()
        }
        
        this.saveConversationsToStorage()
        this.updateHistoryPanel()
      },
      saveConversationsToStorage() {
        try {
          localStorage.setItem('deepseek-chat-conversations', JSON.stringify(this.conversations))
        } catch (e) {
          console.error('保存对话失败:', e)
        }
      },
      loadConversations() {
        try {
          const saved = localStorage.getItem('deepseek-chat-conversations')
          if (saved) {
            this.conversations = JSON.parse(saved)
          }
        } catch (e) {
          console.error('加载对话失败:', e)
        }
      },
      updateHistoryPanel() {
        // 计算属性 sortedConversations 会自动更新
      },
      loadConversation(conversationId) {
        const conversation = this.conversations[conversationId]
        if (!conversation) return
        
        // 设置当前对话
        this.currentConversationId = conversationId
        this.currentRole = conversation.role || this.DEFAULT_ROLE
        this.conversationHistory = [...conversation.history]
        
        // 滚动到底部
        this.$nextTick(() => {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
        })
      },
      clearHistory() {
        if (confirm('确定要清除所有历史记录吗？此操作不可撤销。')) {
          this.conversations = {}
          localStorage.removeItem('deepseek-chat-conversations')
          this.startNewConversation()
        }
      }
    }
  }